<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\controller\api;


use app\common\repositories\store\order\StoreOrderRepository;
use app\common\repositories\system\serve\ServeOrderRepository;
use crmeb\basic\BaseController;
use crmeb\services\PayService;
use crmeb\services\WechatService;
use think\App;
use think\facade\Cache;

class Wechat extends BaseController
{

    /**
     * StoreOrder constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function jsConfig()
    {
        $data = WechatService::create()->jsSdk($this->request->param('url')?:$this->request->host());
        $data['openTagList'] = ['wx-open-launch-weapp'];
        return app('json')->success($data);
    }

    /**
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * 保证金支付
     */
    public function payMargin()
    {
        $payType = $this->request->param('pay_type');
        $merId = $this->request->param('mer_id');
        if (!in_array($payType, StoreOrderRepository::PAY_TYPE, true))
            return app('json')->fail('请选择正确的支付方式');

        $data['type'] = 10; //保证金
        $data['pay_type'] = in_array($payType, ['alipay','alipayQr'], true) ? 2 : 1;

        $isApp = $this->request->isApp();
        if (in_array($payType, ['weixin', 'alipay'], true) && $isApp) {
            $payType .= 'App';
        }

        $user = $this->request->userInfo();
        $res = app()->make(ServeOrderRepository::class)->margin($merId, $data);
        $key = $res['key'];
        $param = $res['param'];
        if(!$result = Cache::store('file')->get($key)){
            $order_sn = app()->make(StoreOrderRepository::class)->getNewOrderId(StoreOrderRepository::TYPE_SN_SERVER_ORDER);
            $param['order_sn'] = $order_sn;
            $param['body'] = $order_sn;
            $service = new PayService($payType,$param);
            $code = $service->pay($user);
            $endtime = time() + 1800 ;
            $result = [
                'config' => $code['config'],
                'endtime'=> date('Y-m-d H:i:s',$endtime),
                'price'  => $param['pay_price']
            ];
            Cache::store('file')->set($key,$result,30);
            $param['key'] = $key;
            Cache::store('file')->set($order_sn,$param,60 * 24);
        }
        return app('json')->success($result);
    }
}
